class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0) return 0;
        int first = FirstT(nums,target);
        int last = LastT(nums,target);
        if(first < 0 || last < 0) return 0;
        return last - first + 1;
    }

    public int FirstT(int[] arr,int k){
        int left = 0;
        int right = arr.length - 1;
        while(left + 1 < right){
            int mid = left + (right - left) /2;
            if(arr[mid] >= k){
                right = mid;
            }else{
                left = mid;
            }
        }
        if(arr[left] == k) return left;
        if(arr[right] == k) return right;
        return -1;
    }

    public int LastT(int[] arr,int k){
        int left = 0;
        int right = arr.length - 1;
        while(left + 1 < right){
            int mid = left + (right - left) /2;
            if(arr[mid] > k){
                right = mid;
            }else{
                left = mid;
            }
        }
        if(arr[right] == k) return right;
        if(arr[left] == k) return left;
        return -1;
    }

}

